package com.pangu.web.handler.admin;



import com.pangu.core.BMDataContext;
import com.pangu.util.BeiMiDic;
import com.pangu.web.handler.Handler;
import com.pangu.web.handler.admin.shiro.ShiroUtils;
import com.pangu.web.handler.admin.utils.*;
import com.pangu.web.handler.admin.utils.IPWhiteList;
import com.pangu.web.model.IpWhiteList;
import com.pangu.web.service.repository.jpa.IpWhiteListRepository;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/** 
 * @author Chris 
 * @date 2018/3/26 13:22
 * @todo  登录控制层
*/
@Controller
public class AdminLoginController extends Handler{

	@Autowired
	private IpWhiteListRepository ipWhiteListRepository;

	
/*	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}*/

	/**
	 * 获取验证码（Gif版本）
	 * @param response
	 */
	@RequestMapping(value="/getGifCode",method= RequestMethod.GET)
	public void getGifCode(HttpServletResponse response){
		try {
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("image/gif");
			/**
			 * gif格式动画验证码
			 * 宽，高，位数。
			 */
			Captcha captcha = new GifCaptcha(146,42,4);
			//输出
			ServletOutputStream out = response.getOutputStream();
			captcha.out(out);
			out.flush();
			//存入Shiro会话session
			String vcode=captcha.text().toLowerCase();
			System.out.println( vcode);
			TokenManager.setVal2Session(VerifyCodeUtils.V_CODE, vcode);
		} catch (Exception e) {

		}
	}

	/**
	 * @author Chris
	 * @date 2018/4/20 18:58
	 * @todo   跳转到首页
	*/
	@RequestMapping("/index")
	public ModelAndView admin(HttpServletRequest request, ModelAndView view) {
		/*view.addObject("gameTypeList", BeiMiDic.getInstance().getDic(BMDataContext.BEIMI_SYSTEM_GAME_TYPE_DIC)) ;*/
		return  new ModelAndView("/index","gameTypeList",BeiMiDic.getInstance().getDic(BMDataContext.BEIMI_SYSTEM_GAME_TYPE_DIC));
		/*return request(super.createRequestPageTempletResponse("/index"));*/
	}
	
	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public Map<String,Object> login(String username, String password, String vcode,HttpServletRequest request) {
		//判断验证码是否正确
	    /*
	     if(!VerifyCodeUtils.verifyCode(vcode)){
			log.error("【##】 VCode is Incorrect");
			resultMap.put("message","验证码错误");
			return resultMap;
		}*/

     	String ip= IPUtils.getIpAddr(request);
		if(!isInIpWhiteList(ip)){
			resultMap.put("message","IP不能访问,请联系管理员！");
			return resultMap;
		}
		try{
			Subject subject = ShiroUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			subject.login(token);
		}catch (UnknownAccountException e) {
			resultMap.put("message","账号或者密码错误");
			return resultMap;
		}catch (IncorrectCredentialsException e) {
			resultMap.put("message","账号或者密码错误");
			return resultMap;
		}catch (LockedAccountException e) {
			resultMap.put("message","账号已被锁定，请联系管理员！");
			return resultMap;
		}catch (AuthenticationException e) {
			resultMap.put("message","账号验证失败");
			return resultMap;
		}
	    resultMap.put("message","success");
		return resultMap;
	}
	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login.html";
	}

	/** 
	 * @author Chris 
	 * @date 2018/3/31 13:21
	 * @todo  判断验证码是否在白名单内 
	*/ 
	private boolean isInIpWhiteList(String ip){

		List<IpWhiteList> allowIps=ipWhiteListRepository.findAll();
		for(IpWhiteList ipStr:allowIps){
			if(IPWhiteList.checkLoginIP(ip,ipStr.getIp())){
				return true;
			}
		}

		return false;
	}
	
}
